//////////////////////////////////////////////////////////////////////////
//             Copyright 2014  All Rights Reserved                //
//////////////////////////////////////////////////////////////////////////
/* =======================================================================
 * 系统名   : 
 * 子系统名 : 
 * Class名  : FormatSql.java
 * 概要     : 
 * 改版履历 : 
 * 版本                     日期                    作者名             备注
 * 1.0.0    2015年5月7日        郭恩洲          初次作成
 * ======================================================================= */
package common;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class FormatSql {

	public static void main(String[] args) throws IOException {
		ArrayList<String> strArr = readFromFile();
		formatSQL(strArr);
		OutputFormatSql(strArr);

	}

	private static void formatSQL(ArrayList<String> strArr) {
		String tmpCurrLine;
		String tmpNextLine;
		for (int i = 0; i < strArr.size(); i++) {
			tmpCurrLine = strArr.get(i);
			// consider last line
			if (strArr.size() == (i + 1)) {
				tmpNextLine = "";
			} else {
				tmpNextLine = strArr.get(i + 1);
				formatSqlLine(tmpCurrLine, tmpNextLine, strArr, i);
			}

		}
	}

	private static void OutputFormatSql(ArrayList<String> strArr) {
		for (int i = 0; i < strArr.size(); i++) {
			System.out.println(strArr.get(i));
		}
	}

	private static void formatSqlLine(String tmpCurrLine, String tmpNextLine,
			ArrayList<String> strArr, int i) {
		String tmpCurrFormatLine;
		String tmpCurrLeftLine;
		for (int j = tmpCurrLine.length() - 1; j > 0;) {
			if (tmpCurrLine.charAt(j) == ' ') {
				tmpCurrFormatLine = tmpCurrLine.substring(0, j);
				tmpCurrLeftLine = tmpCurrLine.substring(j + 1,
						tmpCurrLine.length()); // keep last space
				strArr.set(i, tmpCurrFormatLine);
				strArr.set(i + 1, tmpCurrLeftLine + tmpNextLine);
				tmpNextLine = tmpCurrLeftLine + tmpNextLine;
				// System.out.println(tmpCurrFormatLine);
				// System.out.println(tmpCurrLeftLine);
				// System.out.println(tmpNextLine);
				break;
			} else {
				j--;
			}
		}
	}

	private static ArrayList<String> readFromFile()
			throws FileNotFoundException, IOException {
		ArrayList<String> strArr = new ArrayList<String>();
		FileReader reader = new FileReader("e://a.sql");
		BufferedReader br = new BufferedReader(reader);
		String str = null;
		while ((str = br.readLine()) != null) {
			strArr.add(str);
		}
		br.close();
		reader.close();
		return strArr;
	}

}